//
//  HistoryListCollectionCell.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/3/25.
//

import UIKit

/// 当前按钮选中类型
enum SelectType {
    case week
    case month
    case year
}

let HistoryListCollectionCellId = "HistoryListCollectionCell"

class HistoryListCollectionCell: UICollectionViewCell, ChartViewDelegate {
    
    /// 当前选中按钮
    var currentSelectBtn = SelectType.week
    var chartView: ScatterChartView!
    //所有点的颜色
    var circleColors: [UIColor] = []
    var dataArray = [RModel]()
    var startTimeStamp = Int()
    var endTimeStamp = Int()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        initScatterChart()
    }
    
    /// 散点图
    func initScatterChart() {
        //创建散点图组件对象
        chartView = ScatterChartView()
        chartView.delegate = self
        chartView.frame = CGRect(x: 20, y: 0, width: kScreenWidth - 40, height: self.height)
        chartView.legend.form = .none // 图例
        chartView.legend.textColor = .clear
        chartView.xAxis.labelPosition = .bottom //x轴显示在下方
        chartView.xAxis.axisLineColor = hexColor("F3F3F3")! //x轴颜色
        chartView.xAxis.axisLineWidth = 0.8 // 线宽
        chartView.leftAxis.gridColor = hexColor("F3F3F3")!
        chartView.leftAxis.gridLineWidth = 1 // 线宽
        chartView.xAxis.drawGridLinesEnabled = false //不绘制网格线
        chartView.rightAxis.enabled = false //禁用右侧的Y轴
        chartView.leftAxis.drawAxisLineEnabled = false //不显示左侧Y轴
        chartView.leftAxis.axisMinimum = 80 //最小刻度值
        chartView.leftAxis.axisMaximum = 100 //最大刻度值
        chartView.leftAxis.granularity = 5 //最小间隔
        chartView.noDataText = "暂无数据"
        chartView.noDataTextAlignment = .center
        self.addSubview(chartView)
        
    }
    
    /// 刷新图表数据
    func loadChartViewData(historyData: [RModel]) {
        
        circleColors.removeAll()
        dataArray.removeAll()
        
        var timeLimit = 86400 // 一天的秒数
        if self.currentSelectBtn == .year {
            timeLimit *= 30
        }
        
        var timeInterval = [Int]()
        self.addInterval(startStamp: endTimeStamp, currentStamp: startTimeStamp, interval: timeLimit, timeInterval: &timeInterval)
        // 创建 timeInterval.count - 1 个空数组，便利本地数据，存储到对应的时间间隔里
        var allDataArray = [[RModel]](repeating: [RModel](), count: timeInterval.count - 1)
        
        // 当前选中时间段数据源 取出来的时间戳，放到对应的时间段的index里
        for model in historyData {
            for (index, time) in timeInterval.enumerated() {
                if index > 0, Int(model.timeStamp) > time, Int(model.timeStamp) < timeInterval[index - 1] {
                    allDataArray[index - 1].append(model)
                    break
                }
            }
        }
        
        // 取出每天最小的spo2
        for (i, array) in allDataArray.enumerated() {
            
            if array.count > 0 {
                var spo2 = 100, index = 0
                for (j, model) in array.enumerated() {
                    if model.spo2 > 80 {
                        if model.spo2 < spo2 {
                            spo2 = model.spo2
                            index = j
                        }
                    }
                }
                self.dataArray.append(array[index])
            }else {
                
                let model = RModel.init(fromeLocal: timeInterval[i])
                self.dataArray.append(model)
            }
            
        }
        
        // 取出每个时间段内最低的SpO2
        var dataEntries = [ChartDataEntry]()
        var xValus = [String]()
        for (index, obj) in self.dataArray.enumerated() {
            circleColors.append(hexColor("3468E2")!)
            dataEntries.append(ChartDataEntry(x: Double(index), y: Double(obj.spo2)))
            
            if self.dataArray.count / 6 > 1 {
                
                let count = self.dataArray.count / 6
                var add = false
                for number in 0...count {
                    if index == number * 6 {
                        xValus.append(formatTimeStamp(time: obj.timeStamp, format: "MM-dd"))
                        add = true
                    }
                }
                if add == false {
                    xValus.append("")
                }
                
            }else {
                xValus.append(formatTimeStamp(time: obj.timeStamp, format: "MM-dd"))
            }
            
        }
        
        chartView.scaleYEnabled = false //取消Y轴缩放
        chartView.doubleTapToZoomEnabled = false //双击缩放
        chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValus) // 横坐标
        chartView.xAxis.labelCount = xValus.count
        let chartDataSet = ScatterChartDataSet(entries: dataEntries)
        chartDataSet.setColor(hexColor("3468E2") ?? NSUIColor.init())
        chartDataSet.setScatterShape(.circle) //使用圆形散点
        chartDataSet.drawValuesEnabled = false //不绘制拐点上的文字
        chartDataSet.highlightColor = hexColor("3468E2")! //十字线颜色
        chartDataSet.highlightLineWidth = 1 //十字线线宽
        chartDataSet.drawHorizontalHighlightIndicatorEnabled = false //不显示横向十字线
        
        let chartData = ScatterChartData(dataSet: chartDataSet)
        chartView.data = chartData
    }
    
    /// 根据时间间隔分成n个数组  当前时间 -- (当前时间 - 间隔) -- (当前时间 - 间隔) -- 开始时间(2022-1-1)
    @discardableResult
    func addInterval(startStamp: Int, currentStamp: Int, interval: Int, timeInterval: inout [Int]) -> [Int] {
        let current = currentStamp
        if currentStamp > startStamp {
            timeInterval.append(current)
            addInterval(startStamp: startStamp, currentStamp: current - interval, interval: interval, timeInterval: &timeInterval)
        }else {
            timeInterval.append(startStamp)
        }
        return timeInterval
    }
    
    //折线上的点选中回调
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        
        //将选中的数据点的颜色改成黄色
        var chartDataSet = ScatterChartDataSet()
        chartDataSet = (chartView.data?.dataSets[0] as? ScatterChartDataSet)!
        let values = chartDataSet.entries
        let index = values.firstIndex(where: {$0.x == highlight.x})  //获取索引
        chartDataSet.colors = circleColors//还原
        chartDataSet.colors[index!] = .orange
        
        //重新渲染表格
        chartView.data?.notifyDataChanged()
        chartView.notifyDataSetChanged()
        
        // 显示MarkerView标签
        let model = self.dataArray[Int(entry.x)]
        // 时间
        let time = formatTimeStamp(time: model.timeStamp, format: "MM/dd")
        self.chartView.marker = MarkerBaseView.configView(chartView: self.chartView, title: "\(time)", value: "\(Int(entry.y))")
    }
    
    //折线上的点取消选中回调
    func chartValueNothingSelected(_ chartView: ChartViewBase) {
        print("取消选中的数据")
        
        //还原所有点的颜色
        var chartDataSet = ScatterChartDataSet()
        chartDataSet = (chartView.data?.dataSets[0] as? ScatterChartDataSet)!
        chartDataSet.colors = circleColors
        
        //重新渲染表格
        chartView.data?.notifyDataChanged()
        chartView.notifyDataSetChanged()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
